﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using KSUNO_EMS.Models;

namespace KSUNO_EMS.Controllers
{
    public class ScheduleManagementController : EmsController
    {
        public ActionResult Index()
        {
            return (ActionResult)VerifyAccess("Manager") ?? View();
        }

        [HttpGet]
        public ActionResult GetSchedule(DateTime date)
        {
            var firstDayOfWeek = date.Subtract(new TimeSpan((int)date.DayOfWeek, 0, 0, 0));
            var lastDayOfWeek = date.Add(new TimeSpan(7 - (int)date.DayOfWeek, 0, 0, 0));

            return new ProperJsonResult
                       {
                           Data = new AjaxResult(true,
                                                 new
                                                     {
                                                         Date = firstDayOfWeek,
                                                         Schedules = Database.Employees.ToList()
                                                     .Select(employee =>
                                                         EmployeeScheduleDTO.FromDatabase(employee, employee.ScheduledDateTimes
                                                                 .Where(s => s.StartDateTime >= firstDayOfWeek && s.StartDateTime <= lastDayOfWeek)))
                                                     }),
                                                 //      Data = new AjaxResult(true,
                                                 //new
                                                 //    {
                                                 //        Date = firstDayOfWeek,
                                                 //        Schedules = Database.Employees.ToList()
                                                 //    .Select(employee =>
                                                 //            new
                                                 //                {
                                                 //                    Id = employee.Id,
                                                 //                    Employee = employee.FirstName + " " + employee.LastName,
                                                 //                    Schedule = employee.ScheduledDateTimes
                                                 //                .Where(s => s.StartDateTime >= firstDayOfWeek && s.StartDateTime <= lastDayOfWeek)
                                                 //                .Select(s => new { StartDate = s.StartDateTime, EndDate = s.EndDateTime })
                                                 //                })
                                                 //    }),
                           HasDates = true
                       };
        }

        public ActionResult GenerateSchedule(DateTime date)
        {
            //schedule.Deserialise<>()


            return new ProperJsonResult { Data = new AjaxResult(true) };
        }
        enum Days
        {
            Monday = 0,
            Tuesday = 1,
            Wednesday = 2,
            Thursday = 3,
            Friday = 4,
            Saturday = 5,
            Sunday = 6
        }
        public ActionResult UpdateSchedule(DateTime date, string schedule)
        {
            var firstDayOfWeek = date.Subtract(new TimeSpan((int)date.DayOfWeek, 0, 0, 0)).AddDays(1);
            var lastDayOfWeek = date.Add(new TimeSpan(7 - (int)date.DayOfWeek, 0, 0, 0)).AddDays(1);

            var employeeSchedule = schedule.Deserialise<IEnumerable<EmployeeScheduleDTO>>();
            foreach (var employee in employeeSchedule)
            {
                var dbEmployee = Database.Employees.SingleOrDefault(s => s.Id == employee.Id);
                if (dbEmployee == null)
                    continue;
                foreach (var scheduleEntry in dbEmployee.ScheduledDateTimes.Where(d => d.StartDateTime >= firstDayOfWeek && d.StartDateTime <= lastDayOfWeek).ToList())
                    Database.EmployeeSchedules.Remove(scheduleEntry);
                
                Database.SaveChanges();

                if (employee.Monday != null)
                    CreateScheduleEntries(dbEmployee, firstDayOfWeek, Days.Monday, employee.Monday);

                Database.SaveChanges();
            }

            return new ProperJsonResult { Data = new AjaxResult(true) };
        }
        private static void CreateScheduleEntries(Employee employee, DateTime firstDayOfWeek, Days day, string entry)
        {
            entry = entry.Replace(", ", ",");
            foreach (var scheduleEntry in entry.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(e => e.Split(new char[] { '-' })).Select(t => new { From = ParseTime(t[0]), To = ParseTime(t[1]) }))
            {
                employee.ScheduledDateTimes.Add(new EmployeeSchedule()
                                                    {
                                                        StartDateTime = firstDayOfWeek.AddDays((int)day).AddHours(scheduleEntry.From.Hour).AddMinutes(scheduleEntry.From.Minute),
                                                        EndDateTime = firstDayOfWeek.AddDays((int)day).AddHours(scheduleEntry.To.Hour).AddMinutes(scheduleEntry.To.Minute)
                                                    });
            }
        }
        private static DateTime ParseTime(string timeString)
        {
            if (!Regex.IsMatch(timeString.ToUpper(), "(AM)|(PM)"))
                timeString += Convert.ToInt32(Regex.Match(timeString, @"^\d+").Value) < 12 ? "PM" : "AM";

            //if (!timeString.Contains(":"))
            //    timeString = Regex.Replace(timeString, @"\s*((AM)|(PM))", ":00 $1");
            return DateTime.Parse(timeString);
        }
    }
}
